<template>
  <div class="box_per">
    <div>
      <input type="text" v-model="txtvalus">
      <button @click="clids">
        发送
      </button>
      <div v-for="(item,index) in listdata" :key="index">
        <p>
          <span>{{ item.name }}：</span> {{ item.conts }}
        </p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "childList",
  data() {
    return {
      websock: null,
      txtvalus: "",
      listdata: []
    };
  },
  created() {
    this.initWebSocket();
  },
  methods: {
    initWebSocket() { //初始化weosocket
      const wsuri = `ws://localhost:8080/user`;
      this.websock = new WebSocket(wsuri);
      this.websock.onmessage = this.websocketonmessage;
      this.websock.onopen = this.websocketonopen;
      this.websock.onerror = this.websocketonerror;
      this.websock.onclose = this.websocketclose;
    },
    websocketonopen() { //连接建立
      console.log("连接成功");
    },
    websocketonerror() {//连接建立失败重连
      console.log("websocket错误：");
    },
    websocketonmessage(evtev) {
      console.log(JSON.parse(evtev.data), "返回数据")
      this.listdata.push(JSON.parse(evtev.data))
    },
    websocketclose(e) {  //关闭
      console.log('断开连接', e);
    },
    clids() {
      let data = {
        name: "王",
        conts: this.txtvalus
      }
      this.websock.send(JSON.stringify(data))
    }

  },
};
</script>

<style scoped>
</style>